package cn.com.libertymutual.production.service.impl.business;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import cn.com.libertymutual.production.model.nomorcldatasource.*;
import cn.com.libertymutual.production.pojo.request.PrpdClauseRequest;
import cn.com.libertymutual.production.pojo.response.Response;
import cn.com.libertymutual.production.service.api.business.ClauseBusinessService;
import cn.com.libertymutual.production.utils.Constant.BUSINESSLOGTYPE;
import cn.com.libertymutual.production.utils.Constant.OPERTYPE;
import cn.com.libertymutual.production.utils.ObjectUtil;

import com.github.pagehelper.PageInfo;

/**
 * 事务管理注意事项：
 * 1. 新增/修改操作必须启用事务
 * 2. 方法体内部抛出异常即可启用事务
 * @author Steven.Li
 * @date 2017年7月28日
 * 
 */
@Service
@Transactional(rollbackFor = Exception.class, transactionManager = "transactionManagerCoreData")
public class ClauseBusinessServiceImpl extends ClauseBusinessService {

	@Override
	public Response findPrpdClause(PrpdClauseRequest prpdClauseRequest) {
		Response result = new Response();
		try {
			PageInfo<PrpdclauseWithBLOBs> pageInfo = prpdClauseService
					.findPrpdClause(prpdClauseRequest);
			result.setTotal(pageInfo.getTotal());
			result.setResult(pageInfo.getList());
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response findPrpdClauseCodeNo() {
		Response result = new Response();
		try {
			result.setResult("SE" + prpMaxNoService.findMaxNo("prpdclause"));
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	public static void main(String[] args) {
		String t = "1.条款历史数据迁移\n"
				+"2.责任历史数据迁移\n"
				+"3.方案历史数据迁移（没有默认方案的，比如2725）\n"
				+"4.2724方案增加了字段需要刷数。（字段free1、2、3）\n"
				+"5.投保单、保单需要刷数处理。（主要刷算费方式哪个字段。）\n"
				+"6.3101、3103方案以前是C，现在改成B（关联关系表和方案表都要改）\n"
				+"   原因：统一规则a\b由ILOG算费，B/C由程序算费。\n"
				+"7.责任表，父级、子级、无层级 这个字段需要刷数处理\n"
				+"8.prpditem表中同一个ITEMCODE对应多个RISKCODE需要刷数处理\n"
				+"9.特约，机构代码以前是2位，现在是8位，以前的数据要刷数处理。\n"
				+"10.短期费率表需要用户提供写入数据库\n"
				+"11.产品管理的权限列表需要用户提供写入数据。\n"
				+"12.主险条款以前是否累积保额是程序写死（主险都是累积），现在要读取配置，需要刷数处理\n"
				+"13.条款关联责任关系表，以前的历史数据需要刷数处理。\n"
				+"14.2724更改权限，需要把Prpdriskplan表的applycomcode刷成ALL\n"
				+"15.31线，以前配置的产品同一个条款配置到多个计划中就有多条数据，导致现在新逻辑显示要出现重复数据，需要SQL将其他置为无效只保留1条有效数据。\n"
				+"16.产品管理系统中，已关联险种和已关联责任数据同样需要刷数处理。";
		char[] out = t.toCharArray();
		StringBuffer lineContent = new StringBuffer();
		for(int i = 0; i < out.length; i++) {
			lineContent.append(out[i]);
			if ((i+1) % 20 == 0 || (i+1) == out.length) {
				System.out.println(lineContent);
				lineContent = new StringBuffer();
			}
		}
	}
	
	@Override
	public Response insertPrpdClause(PrpdClauseRequest request)
			throws Exception {
		Response result = new Response();
		StringBuffer clauseDetails = new StringBuffer();
		try {
			PrpdclauseWithBLOBs prpdclause = new PrpdclauseWithBLOBs();
			prpdclause.setClausecode(request.getClausecode());
			prpdclause.setClausename(request.getClausename());
			prpdclause.setLanguage(request.getLanguage());
			prpdclause.setTitleflag("1");
			prpdclause.setLineno("1");
			prpdclause.setContext(request.getClausename());
			prpdclause.setNewclausecode(request.getClausecode());
			prpdclause.setValidstatus(request.getValidstatus());
			if(!StringUtils.isEmpty(request.getComcode()) && request.getComcode().contains("ALL")) {
				prpdclause.setComcode("ALL");
			} else {
				prpdclause.setComcode(request.getComcode());
			}
			prpdclause.setContflag(request.getContflag());
			prpdclause.setDelflag(request.getDelflag());
			prpdclause.setIniflag(request.getIniflag());
			prpdclause.setRemark(request.getRemark());
			prpdclause.setAgentcode(request.getAgentcode());
			
			//保存标题数据
			prpdClauseService.insert(prpdclause);
			//保存内容数据
			String content = request.getContext();
			if (!StringUtils.isEmpty(content)) {
				int contentLength = 80; //字符串拆分，长度
				char[] contentChars = content.toCharArray();
				StringBuffer lineContent = new StringBuffer();
				int lineNo = 2;
				for(int i = 0; i < contentChars.length; i++) {
					lineContent.append(contentChars[i]);
					if ((i+1) % contentLength == 0 || (i+1) == contentChars.length) {
						prpdclause.setTitleflag("0");
						prpdclause.setLineno((lineNo++) + "");
						prpdclause.setContext(lineContent.toString());
						prpdClauseService.insert(prpdclause);
						lineContent = new StringBuffer();
					}
				}
			}
			clauseDetails.append("新增特约基础数据:" + ObjectUtil.info(prpdclause) + ";");
			// 保存适用险种到prpdcoderisk
			if (!StringUtils.isEmpty(request.getRiskcode())) {
				PrpdcoderiskKey prpdCodeRisk = new PrpdcoderiskKey();
				prpdCodeRisk.setCodetype("ClauseCode");
				prpdCodeRisk.setCodecode(request.getClausecode());
				String[] riskCodeArry = request.getRiskcode().split(",");
				for (int i = 0; i < riskCodeArry.length; i++) {
					prpdCodeRisk.setRiskcode(riskCodeArry[i]);
					prpdCodeRiskService.insert(prpdCodeRisk);
					clauseDetails.append("新增特约基础数据:" + ObjectUtil.info(prpdCodeRisk) + ";");
				}
			}
			// 保存默认带出险种、默认带出分公司到prpdriskclause
			if (!StringUtils.isEmpty(request.getDefaultriskcode())) {
				PrpdriskclauseWithBLOBs prpdriskclause = new PrpdriskclauseWithBLOBs();
				prpdriskclause.setClausecode(request.getClausecode());
				prpdriskclause.setClausename(request.getClausename());
				prpdriskclause.setValidstatus("1");
				prpdriskclause.setLanguage(request.getLanguage());
				if (StringUtils.isEmpty(request.getPlancode())) {
					prpdriskclause.setPlancode("defaultPlan");
				} else {
					prpdriskclause.setPlancode(request.getPlancode());
				}
				prpdriskclause.setComcode(request.getDefaultcomcode());
				String[] riskCodeArry = request.getDefaultriskcode().split(",");
				for (int i = 0; i < riskCodeArry.length; i++) {
					prpdriskclause.setRiskcode(riskCodeArry[i]);
					prpdRiskClauseService.insert(prpdriskclause);
					clauseDetails.append("新增特约基础数据:" + ObjectUtil.info(prpdriskclause) + ";");
				}
			}
			
			// ********************************************************************************
			// 特约新增日志-保存基础数据
			systemLog.save(
					BUSINESSLOGTYPE.CLAUSE,
					OPERTYPE.INSERT,
					prpdclause.getClausecode(),
					clauseDetails.toString());
			// ********************************************************************************
			String newMaxNo = request.getClausecode().substring(2);
			Prpmaxno prpmaxno = new Prpmaxno();
			prpmaxno.setMaxno((Integer.parseInt(newMaxNo) + 1) + "");
			prpMaxNoService.updateMaxNo(prpmaxno, "prpdclause");
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			throw e;
		}
		return result;
	}

	@Override
	public Response findCodeRiskByClause(String clauseCode) {
		Response result = new Response();
		try {
			List<PrpdcoderiskKey> codeRisks = prpdCodeRiskService.findCodeRiskByCondition("ClauseCode", clauseCode);
			String codeRisk = "";
			if(!codeRisks.isEmpty()) {
				String tempCodeRisk = "";
				for(PrpdcoderiskKey cr : codeRisks) {
					tempCodeRisk += cr.getRiskcode() + ",";
				}
				codeRisk = tempCodeRisk.substring(0, tempCodeRisk.length() - 1);
			}
			result.setResult(codeRisk);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response findRiskClauseByClause(String clauseCode) {
		Response result = new Response();
		try {
			List<PrpdriskclauseWithBLOBs> riskClauses = prpdRiskClauseService.findByCluaseCode(clauseCode);
			result.setResult(riskClauses);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response updatePrpdClause(PrpdClauseRequest request)
			throws Exception {
		Response result = new Response();
		PrpdclauseWithBLOBs prpdClause = new PrpdclauseWithBLOBs();
		Prpdriskclause prpdRiskClause = new Prpdriskclause();
		PrpdcoderiskKey prpdCodeRiskKey = new PrpdcoderiskKey();
		
		StringBuffer clauseDetails = new StringBuffer();
		
		try {
			//组装数据
			prpdClause.setClausecode(request.getClausecode());
			prpdRiskClause.setClausecode(request.getClausecode());
			prpdCodeRiskKey.setCodetype("ClauseCode");
			prpdCodeRiskKey.setCodecode(request.getClausecode());
			
			prpdClauseService.delete(prpdClause);
			prpdRiskClauseService.delete(prpdRiskClause);
			prpdCodeRiskService.delete(prpdCodeRiskKey);
			
			PrpdclauseWithBLOBs prpdclause = new PrpdclauseWithBLOBs();
			prpdclause.setClausecode(request.getClausecode());
			prpdclause.setClausename(request.getClausename());
			prpdclause.setLanguage(request.getLanguage());
			prpdclause.setTitleflag("1");
			prpdclause.setLineno("1");
			prpdclause.setContext(request.getClausename());
			prpdclause.setNewclausecode(request.getClausecode());
			prpdclause.setValidstatus(request.getValidstatus());
			if(!StringUtils.isEmpty(request.getComcode()) && request.getComcode().contains("ALL")) {
				prpdclause.setComcode("ALL");
			} else {
				prpdclause.setComcode(request.getComcode());
			}
			prpdclause.setContflag(request.getContflag());
			prpdclause.setDelflag(request.getDelflag());
			prpdclause.setIniflag(request.getIniflag());
			prpdclause.setRemark(request.getRemark());
			prpdclause.setAgentcode(request.getAgentcode());

			//保存标题数据
			prpdClauseService.insert(prpdclause);
			clauseDetails.append("特约标题数据-修改后:" + ObjectUtil.info(prpdclause) + ";");
			//保存内容数据
			String content = request.getContext();
			if (!StringUtils.isEmpty(content)) {
				int contentLength = 80; //字符串拆分，长度
				char[] contentChars = content.toCharArray();
				StringBuffer lineContent = new StringBuffer();
				int lineNo = 2;
				for(int i = 0; i < contentChars.length; i++) {
					lineContent.append(contentChars[i]);
					if ((i+1) % contentLength == 0 || (i+1) == contentChars.length) {
						prpdclause.setTitleflag("0");
						prpdclause.setLineno((lineNo++) + "");
						prpdclause.setContext(lineContent.toString());
						prpdClauseService.insert(prpdclause);
						lineContent = new StringBuffer();
					}
				}
			}
			
			clauseDetails.append("特约内容数据-修改后:" + ObjectUtil.info(prpdclause) + ";");
			
			// 保存适用险种到prpdcoderisk
			if (!StringUtils.isEmpty(request.getRiskcode())) {
				PrpdcoderiskKey prpdCodeRisk = new PrpdcoderiskKey();
				prpdCodeRisk.setCodetype("ClauseCode");
				prpdCodeRisk.setCodecode(request.getClausecode());
				String[] riskCodeArry = request.getRiskcode().split(",");
				for (int i = 0; i < riskCodeArry.length; i++) {
					prpdCodeRisk.setRiskcode(riskCodeArry[i]);
					prpdCodeRiskService.insert(prpdCodeRisk);
					clauseDetails.append("特约适用险种-修改后:" + ObjectUtil.info(prpdCodeRisk) + ";");
				}
			}
			// 保存默认带出险种、默认带出分公司到prpdriskclause
			if (!StringUtils.isEmpty(request.getDefaultriskcode())) {
				PrpdriskclauseWithBLOBs prpdriskclause = new PrpdriskclauseWithBLOBs();
				prpdriskclause.setClausecode(request.getClausecode());
				prpdriskclause.setClausename(request.getClausename());
				prpdriskclause.setValidstatus("1");
				prpdriskclause.setLanguage(request.getLanguage());
				if (StringUtils.isEmpty(request.getPlancode())) {
					prpdriskclause.setPlancode("defaultPlan");
				} else {
					prpdriskclause.setPlancode(request.getPlancode());
				}
				prpdriskclause.setComcode(request.getDefaultcomcode());
				String[] riskCodeArry = request.getDefaultriskcode().split(",");
				for (int i = 0; i < riskCodeArry.length; i++) {
					prpdriskclause.setRiskcode(riskCodeArry[i]);
					prpdRiskClauseService.insert(prpdriskclause);
					clauseDetails.append("特约默认带出信息-修改后:" + ObjectUtil.info(prpdriskclause) + ";");
				}
			}
			if(!"".equals(clauseDetails)) {
				systemLog.save(
						BUSINESSLOGTYPE.CLAUSE,
						OPERTYPE.UPDATE,
						prpdClause.getClausecode(),
						clauseDetails.toString());
			}
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			throw e;
		}
		return result;
	}
	
}
